package com.medical.literature.user.service.impl;

import com.medical.literature.common.exception.BusinessException;
import com.medical.literature.user.dto.ContactRequest;
import com.medical.literature.user.entity.User;
import com.medical.literature.user.mapper.UserMapper;
import com.medical.literature.user.service.ContactService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 联系支持服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ContactServiceImpl implements ContactService {
    
    private final UserMapper userMapper;

    @Override
    public void processContactRequest(ContactRequest request, Long userId) {
        // 获取用户信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 验证请求数据
        if (request.getName() == null || request.getName().trim().isEmpty()) {
            throw new BusinessException("姓名不能为空");
        }
        
        if (request.getEmail() == null || request.getEmail().trim().isEmpty()) {
            throw new BusinessException("邮箱不能为空");
        }
        
        if (request.getType() == null || request.getType().trim().isEmpty()) {
            throw new BusinessException("问题类型不能为空");
        }
        
        if (request.getDescription() == null || request.getDescription().trim().isEmpty()) {
            throw new BusinessException("问题描述不能为空");
        }
        
        // 记录联系请求日志
        log.info("收到用户联系支持请求 - 用户ID: {}, 姓名: {}, 邮箱: {}, 问题类型: {}, 问题描述: {}", 
                userId, request.getName(), request.getEmail(), request.getType(), request.getDescription());
        
        // 这里可以添加实际的处理逻辑，比如：
        // 1. 发送邮件给技术支持
        // 2. 保存到数据库
        // 3. 创建工单等
        
        // 模拟处理过程
        try {
            // 模拟邮件发送
            sendContactEmail(request, user);
            log.info("联系支持请求处理完成");
        } catch (Exception e) {
            log.error("处理联系支持请求时发生错误", e);
            throw new BusinessException("处理联系支持请求失败");
        }
    }
    
    /**
     * 发送联系邮件（模拟实现）
     */
    private void sendContactEmail(ContactRequest request, User user) {
        // 实际项目中这里会集成邮件服务
        log.info("模拟发送联系邮件给技术支持: {}", request.getEmail());
    }
}